package common

import (
	"errors"
	"math"
)

func Sum(arr []int) int {
	total := 0
	for _, num := range arr {
		total += num
	}
	return total
}

func GetPosition(WidthList []int, CurPosition int) (int, error) {
	widthCur := 0
	for i, width := range WidthList {
		if widthCur > CurPosition {
			return i - 1, nil
		}
		widthCur += width
	}
	return 0, errors.New("获取位置失败")
}

// ConvertToAlphabet 将数字转成表格中那种由大写字母组合的26进制，从1开始
func ConvertToAlphabet(num int) string {
	if num <= 0 {
		return ""
	}
	result := ""
	for num > 0 {
		m := num % 26
		if m == 0 {
			m = 26
		}
		result = string(byte(m+'A'-1)) + result
		num = (num - m) / 26
	}
	return result
}

// LettersToNumber 将列字母转换为数字索引 (A=0, B=1, ..., Z=25, AA=26, ...)
func LettersToNumber(letters string) int {
	result := 0
	for _, char := range letters {
		if char >= 'A' && char <= 'Z' {
			result = result*26 + int(char-'A')
		} else if char >= 'a' && char <= 'z' {
			result = result*26 + int(char-'a')
		} else {
			// 非字母字符，返回-1表示无效
			return -1
		}
	}
	// 对于多字符列名，需要调整计算
	if len(letters) > 1 {
		result += int(math.Pow(26, float64(len(letters)-1))) - 1
	}
	return result
}

// NumberToLetters 将数字索引转换为列字母 (0=A, 1=B, ..., 25=Z, 26=AA, ...)
func NumberToLetters(number int) string {
	if number < 0 {
		return ""
	}

	result := ""
	for number >= 0 {
		result = string(byte(number%26+'A')) + result
		number = number/26 - 1
		if number < 0 {
			break
		}
	}
	return result
}
